#include "event_loop_thread.h"
#include "event_loop.h"

EventLoopThread::EventLoopThread() = default;

EventLoopThread::~EventLoopThread() {
    {
        std::lock_guard<std::mutex> lk(mutex_);
        exiting_ = true;
    }
    if (loop_) {
        loop_->runInLoop([loop = loop_] { loop->quit(); });
    }
    if (thread_.joinable()) {
        thread_.join();
    }
}

EventLoop& EventLoopThread::startLoop() {
    thread_ = std::thread([this] { threadFunc(); });

    std::unique_lock<std::mutex> lk(mutex_);
    cond_.wait(lk, [this] { return loop_ != nullptr; });
    return *loop_;
}

void EventLoopThread::threadFunc() {
    EventLoop loop;  // 在线程内构造 EventLoop

    {
        std::lock_guard<std::mutex> lk(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }

    loop.loop();  // 进入事件循环

    std::lock_guard<std::mutex> lk(mutex_);
    loop_ = nullptr;
}